#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QHostAddress>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTextCodec>
Widget::Widget(QWidget *parent)
    : QWidget(parent),serialPort(NULL)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    mqttClient=new QMqttClient(this);
    mqtt_connect();//mqtt连接
    serialPort_open();//打开串口
    horizontalSlider_nowValue();//获取滑动条当前值
    if(ui->lampClose_rbtn->isChecked())
    {
        ui->horizontalSlider->setEnabled(false);//关灯则亮度条无法调节
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::serialPort_open()
{
    serialPort=new QSerialPort(this);
    //serialPort->setPortName("/dev/ttyUSB0");
    QList <QSerialPortInfo> list = QSerialPortInfo::availablePorts();
    serialPort->setPortName(list[0].portName());
    qDebug()<<list[0].portName();
    serialPort->setBaudRate(QSerialPort::Baud115200);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setDataBits(QSerialPort::Data8);
    bool flag=serialPort->open(QSerialPort::ReadWrite);
    if(flag)
    {
        qDebug()<<"Open successfully!";
        connect(serialPort,&QSerialPort::readyRead,this,&Widget::recv_portData);
    }
    else
    {
       qDebug()<<"Can not open serial!";
       qDebug()<<serialPort->error();
       QMessageBox::information(NULL, "提示", "端口无法打开，请重新插入试试！");
       return;
    }
}
//串口接收数据
void Widget::recv_portData()
{
    QByteArray buff;
    buff=serialPort->readAll();//接收数据
    if(buff.length() !=0)
        {
            if(buff.contains("[")&&buff.contains("]")){//判断数据是否包含[]头尾标识符
                QString str = buff;
                QStringList listData = str.split(",");//按逗号作为分割符
                qDebug()<<listData;
                ui->light_txt->setText(listData[1]);
                ui->temp_txt->setText(listData[2]);
                ui->humid_txt->setText(listData[3]);
                //数据按JSON格式处理
                QString data="{\'params\':{\'lightLux\':"+listData[1]+",\'temperature\':"+listData[2]+",\'humidity\':"+listData[3]+"}}";
                if(mqttClient->state()==QMqttClient::Connected)
                {
                    //发布主题
                    mqttClient->publish(QMqttTopicName("/sys/a1w8Wn3cwTK/gateway/thing/event/property/post"),data.toLocal8Bit());
                    qDebug()<<"pub success";
                }
            }
        }
        buff.clear();//清空缓冲区
}
//串口发送数据
void Widget::serialPort_write(QByteArray data)
{
    if(serialPort->isOpen())
    {
        serialPort->write(data);
    }
    else
    {
        QMessageBox::information(NULL, "提示", "端口未打开，无法发送数据！");
    }
}

void Widget::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    serialPort->close();
    qDebug()<<"close serialPort!";
}
//mqtt连接函数
void Widget::mqtt_connect()
{
    mqttClient->setHostname("a1w8Wn3cwTK.iot-as-mqtt.cn-shanghai.aliyuncs.com");
    mqttClient->setPort(1883);
    mqttClient->setClientId("gateway|securemode=3,signmethod=hmacsha1,timestamp=789|");
    mqttClient->setUsername("gateway&a1w8Wn3cwTK");
    mqttClient->setPassword("5459bc324f711a0498c5916674037fff2dc1edd3");
    mqttClient->connectToHost();
    connect(mqttClient,&QMqttClient::connected,this,&Widget::mqtt_subscribe);
}

//订阅主题函数
void Widget::mqtt_subscribe()
{
    if(mqttClient->state()==QMqttClient::Connected)
    {
        //qDebug()<<"connect sucessfully!";
        mqttClient->subscribe(QMqttTopicFilter("/sys/a1w8Wn3cwTK/gateway/thing/service/property/set"));
        connect(mqttClient,&QMqttClient::messageReceived,this,&Widget::recv_mqttData);
        qDebug()<<"subscribe success!";
    }
}

//订阅主题后，接收移动端数据
void Widget::recv_mqttData(QByteArray msg, QMqttTopicName topic)
{
    QJsonParseError jsonError;
    if(topic.name()=="/sys/a1w8Wn3cwTK/gateway/thing/service/property/set")
    {
        QJsonDocument doucment = QJsonDocument::fromJson(msg, &jsonError);
        qDebug()<<doucment;
        if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError)) {
            if (doucment.isObject()) {
                QJsonObject object = doucment.object();
                qDebug()<<object;
                if (object.contains("fanState")) {
                    QJsonValue   value = object.value("fanState");
                    qDebug()<<value;
                    if(value.isDouble())
                    {
                        int fanState = value.toVariant().toInt();
                        qDebug()<<fanState;
                        if(fanState==1)
                        {
                            serialPort_write("a");
                            ui->fanOpen_rbtn->setChecked(true);
                        }
                        else if(fanState==0)
                        {
                            serialPort_write("b");
                            ui->fanClose_rbtn->setChecked(true);
                        }
                        qDebug() << "fanState: " << fanState;
                    }
                }
                if (object.contains("lampState")) {
                    QJsonValue value = object.value("lampState");
                    if(value.isDouble())
                    {
                        int lampState = value.toVariant().toInt();
                        if(lampState>0)
                        {
                            if(lampState==10){
                                 serialPort_write(QByteArray::number(9));//将int转QByteArray
                            }else{
                            serialPort_write(QByteArray::number(lampState));//将int转QByteArray
                            }
                            if(!ui->horizontalSlider->isEnabled())
                            {
                                ui->horizontalSlider->setEnabled(true);
                            }
                            ui->horizontalSlider->setValue(lampState);
                            ui->lampOpen_rbtn->setChecked(true);
                            qDebug() << "lampState : " << lampState;
                        }
                        if(lampState==0)
                        {
                            serialPort_write(QByteArray::number(lampState));

                            if(ui->horizontalSlider->isEnabled())
                            {
                                ui->horizontalSlider->setEnabled(false);
                            }
                            on_lampClose_rbtn_clicked();
                            ui->lampClose_rbtn->setChecked(true);
                            qDebug() << "lampState : " << lampState;
                        }

                    }
                }
            }
        }
        qDebug()<<"data:"+msg;
        qDebug()<<topic.name();
    }

}


void Widget::horizontalSlider_nowValue()
{
    int val = ui->horizontalSlider->value();
    ui->lightValue_txt->setText(QString::number(val));
}


void Widget::on_horizontalSlider_valueChanged(int value)
{
    ui->lightValue_txt->setText(QString::number(value));
    if(value<10&&!ui->lampClose_rbtn->isChecked())
    {
        serialPort_write(QByteArray::number(value));
    }
    if(value>=10&&!ui->lampClose_rbtn->isChecked())
    {
        serialPort_write("9");//最亮等级
    }
    qDebug()<<value;
}

void Widget::on_fanOpen_rbtn_clicked()
{
    serialPort_write("a");
    qDebug()<<"fanOpen";

}

void Widget::on_fanClose_rbtn_clicked()
{
    serialPort_write("b");
    qDebug()<<"fanClose";

}

void Widget::on_lampOpen_rbtn_clicked()
{
    serialPort_write("9");
    ui->horizontalSlider->setEnabled(true);
    ui->horizontalSlider->setValue(10);
    qDebug()<<"open";
}

void Widget::on_lampClose_rbtn_clicked()
{
    serialPort_write("0");
    ui->horizontalSlider->setEnabled(false);//关灯则亮度条无法调节
    qDebug()<<"close";
}
